from typing import List

from fastapi import APIRouter, HTTPException
from sqlmodel import Session, select

from ..db import engine, init_db
from ..models import Server
from ..schemas import ServerCreate, ServerRead, ServerUpdate
from ..services.crypto import encrypt_text


router = APIRouter()


# Ensure tables exist on first import
init_db()


@router.get("/", response_model=List[ServerRead])
def list_servers() -> List[ServerRead]:
    with Session(engine) as session:
        servers = session.exec(select(Server)).all()
        return [
            ServerRead(
                id=s.id,
                name=s.name,
                host=s.host,
                port=s.port,
                username=s.username,
                description=s.description,
            )
            for s in servers
        ]


@router.post("/", response_model=ServerRead)
def create_server(payload: ServerCreate) -> ServerRead:
    server = Server(
        name=payload.name,
        host=payload.host,
        port=payload.port,
        username=payload.username,
        password_enc=encrypt_text(payload.password or ""),
        description=payload.description,
    )
    with Session(engine) as session:
        session.add(server)
        session.commit()
        session.refresh(server)
        return ServerRead(
            id=server.id,
            name=server.name,
            host=server.host,
            port=server.port,
            username=server.username,
            description=server.description,
        )


@router.get("/{server_id}", response_model=ServerRead)
def get_server(server_id: int) -> ServerRead:
    with Session(engine) as session:
        server = session.get(Server, server_id)
        if not server:
            raise HTTPException(status_code=404, detail="Server not found")
        return ServerRead(
            id=server.id,
            name=server.name,
            host=server.host,
            port=server.port,
            username=server.username,
            description=server.description,
        )


@router.put("/{server_id}", response_model=ServerRead)
def update_server(server_id: int, payload: ServerUpdate) -> ServerRead:
    with Session(engine) as session:
        server = session.get(Server, server_id)
        if not server:
            raise HTTPException(status_code=404, detail="Server not found")

        if payload.name is not None:
            server.name = payload.name
        if payload.host is not None:
            server.host = payload.host
        if payload.port is not None:
            server.port = payload.port
        if payload.username is not None:
            server.username = payload.username
        if payload.password is not None:
            server.password_enc = encrypt_text(payload.password)
        if payload.description is not None:
            server.description = payload.description

        session.add(server)
        session.commit()
        session.refresh(server)
        return ServerRead(
            id=server.id,
            name=server.name,
            host=server.host,
            port=server.port,
            username=server.username,
            description=server.description,
        )


@router.delete("/{server_id}")
def delete_server(server_id: int) -> dict:
    with Session(engine) as session:
        server = session.get(Server, server_id)
        if not server:
            raise HTTPException(status_code=404, detail="Server not found")
        session.delete(server)
        session.commit()
    return {"status": "deleted"}

